package com.hxd.mall.utils.open

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Environment
import android.widget.ImageView
import com.hexin.locallibrary.permssion.PermissionGrantedCallback
import com.hexin.locallibrary.permssion.PermissionUtils
import com.hxd.mall.R
import com.hxd.mall.utils.open.PictureUtil.choosePic
import com.lzy.imagepicker.ImagePicker
import com.lzy.imagepicker.loader.ImageLoader
import com.lzy.imagepicker.ui.ImageGridActivity
import com.lzy.imagepicker.view.CropImageView
import id.zelory.compressor.Compressor
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException


/**
 * 图片压缩
 */
object PictureUtil {
    fun Context.compress(bitmap: Bitmap, path: String): String {
        val mPath = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES
        ).absolutePath + "/" + System.currentTimeMillis() + ".jpg"
        val mFileLength = 2 * 1024 * 1024
        val length = bitmap.byteCount
        var mResolutionCompress: File? = null
        var mQualityCompress: File? = null
        try {
            if (length > mFileLength) {
                mResolutionCompress = getResolutionCompress(bitmap, path, mPath)
            }
            if (mResolutionCompress != null) {
                if (mResolutionCompress.length() > mFileLength) {
                    try {
                        mQualityCompress = Compressor(this)
                            .setQuality(80)
                            .setCompressFormat(Bitmap.CompressFormat.JPEG)
                            .setDestinationDirectoryPath(mResolutionCompress.path)
                            .compressToFile(mResolutionCompress)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return mQualityCompress?.path ?: (mResolutionCompress?.path ?: path)
    }

    /**
     * 分辨率压缩
     */
    private fun getResolutionCompress(bitmap: Bitmap, mPath: String, savePath: String): File {
        val options = BitmapFactory.Options()
        // 计算缩放比
        options.inSampleSize = calculateInSampleSize(bitmap, 1224, 1)// 短边大于1224进行压缩
        options.inJustDecodeBounds = false
        val file = File(savePath)//将要保存图片的路径
        var bos: BufferedOutputStream? = null
        try {
            bos = BufferedOutputStream(FileOutputStream(file))
            BitmapFactory.decodeFile(mPath, options).compress(Bitmap.CompressFormat.JPEG, 100, bos)
            bitmap.recycle()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            try {
                bos?.flush()
                bos?.close()
                bitmap.recycle()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return file
    }

    /**
     * 计算缩放比
     */
    private fun calculateInSampleSize(bitmap: Bitmap, standardW: Int, standardH: Int): Int {
        val h = bitmap.height
        val w = bitmap.width
        return if (w > h && w > standardW) {
            h / standardW
        } else if (w < h && h > standardH) {
            w / standardW
        } else 1
    }

    public fun isGif(path: String): Boolean {
        if (path.isEmpty()) {
            return false
        }

        return if (path.contains("?")) {
            path.contains(".gif?") || path.contains(".GIF?")
        } else {
            path.endsWith(".gif") || path.endsWith(".GIF")
        }
    }

    fun Activity.choosePic(imageCode: Int, cameraCode: Int) {
        showCameraDialog({
            ImagePicker.getInstance().run {
                imageLoader = object : ImageLoader {
                    override fun clearMemoryCache() {}

                    override fun displayImagePreview(
                        activity: Activity?,
                        path: String?,
                        imageView: ImageView?,
                        width: Int,
                        height: Int
                    ) {
                        imageView?.load(path ?: "", R.drawable.banner_default_icon)
                    }

                    override fun displayImage(
                        activity: Activity?,
                        path: String?,
                        imageView: ImageView?,
                        width: Int,
                        height: Int
                    ) {
                        imageView?.load(path ?: "", R.drawable.banner_default_icon)
                    }
                }  //设置图片加载器
                isShowCamera = true  //显示拍照按钮
                isCrop = true //允许裁剪（单选才有效）
                isMultiMode = false
                isSaveRectangle = true //是否按矩形区域保存
                //selectLimit = 1    //选中数量限制
                style = CropImageView.Style.CIRCLE  //裁剪框的形状
                focusWidth = 600   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
                focusHeight = 600  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
                outPutX = 1000//保存文件的宽度。单位像素
                outPutY = 1000//保存文件的高度。单位像素
            }
        }, {
            PermissionUtils.permissionCheck(
                this,
                arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE),
                "",
                true,
                object :
                    PermissionGrantedCallback {
                    override fun granted() {
                        if (SDCardUtil.checkSD()) {
                            Intent(this@choosePic, ImageGridActivity::class.java).run {
                                putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true) // 是否是直接打开相机
                                startActivityForResult(this, cameraCode)
                            }
                        } else ToastUtil.showToast(getString(R.string.sdcard_permission_fail_tip))
                    }

                    override fun denied() {
                        ToastUtil.showToast(getString(R.string.ocr_permission_fail_tip))
                    }
                })
        }, {
            PermissionUtils.permissionCheck(
                this,
                arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ),
                "",
                true,
                object :
                    PermissionGrantedCallback {
                    override fun granted() {
                        Intent(this@choosePic, ImageGridActivity::class.java).run {
                            startActivityForResult(this, imageCode)
                        }
                    }

                    override fun denied() {
                        ToastUtil.showToast(getString(R.string.permission_tip))
                    }
                })
        })
    }


}
